import json

from django.shortcuts import render

from django.http.response import JsonResponse
from django.views import View
from . import models

class StudentView(View):
    def get(self, request):
        """获取数据"""
        #模型类名.objects.all() #获取模型对应的数据表的模型类对象
        #本质是一个伪列表是可以使用一些列表的操作的（切片，选取）
        model = models.Student.objects.all() #返回的是一些对象
        # print(model, type(model)) #<QuerySet [<Student: 赵华>, <Student: 程星云>, <Student: 陈峰>
        student_list = []
        #QuerySet里面的成员是模型对象，不能直接被json转换为数据，所有我们需要先转化为字典，然后经过json处理才可以使用
        for student in model:
            student_list.append({
                "id": student.id,
                "name": student.name,
                "age": student.age,
                "sex":student.sex,
                "status": student.get_status_display(),
                "classmate":student.classmate,
                "description": student.description,
                "created_time": student.created_time,
                "updated_time": student.updated_time,
            })
        #上方代码也可以一句话搞定（推导式）
        # student_list = [{
        #         "id": student.id,
        #         "name": student.name,
        #         "age": student.age,
        #         "sex":student.sex,
        #         "classmate":student.classmate,
        #         "description": student.description,
        #         "created_time": student.created_time,
        #         "updated_time": student.updated_time,
        #     }for student in model]
        """
        all() 返回的是模型对象列表，如果要获取字典列表，则可以使用values()
        """
        # student_list = models.Student.objects.values('id', 'name')
        # print(student_list)
        # object_list = models.Student.objects.all()
        # student = object_list[0]
        # print(student.id, student.pk)
        # print(student.description)
        # print(student.created_time.strftime('%Y-%m-%d %H:%M:%S')) #输出时间并且设置输出格式！注意百分号
        # #但字段声明之中用到了choices可选值以后，在模型对象中就可以通过student.get_status_display()来获取当前选修的文本提示
        # print(student.status, student.get_status_display())
        # student_list = list(student_list)

        return JsonResponse(student_list, safe=False)

    def post(self, request):
        #1.接收客户端发送的数据
        data = json.loads(request.body)
        print(data)
        #2.参数校验和格式转换

        #3.模型操作 适用基于模型的save()方法
        # """使用save()添加数据"""
        # student = models.Student(
        #     name=data["name"],
        #     age=data["age"],
        #     sex=data["sex"],
        #     status=data["status"],
        #     classmate=data["classmate"],
        #     description=data["description"],
        # )
        # student.save()
        #4.返回结果

        """使用create方法来添加数据"""
        student = models.Student.objects.create(
                name=data["name"],
                age=data["age"],
                sex=data["sex"],
                status=data["status"],
                classmate=data["classmate"],
                description=data["description"],
        )
        data = {
            "id": student.id,
            "name": student.name,
        }
        return JsonResponse(data, safe=False,status=201)

    def put(self, request):
        """跟新数据"""
        data = {}
        return JsonResponse(data, safe=False,status=201)

    def delete(self, request):
        """删除数据"""
        data = {}
        return JsonResponse(data, safe=False,status=204)